const app = getApp()
import {
    showMsg
} from '../../../utils/config.js'
import {
    reqDoorList,
    reqInfraredList,
    reqCommand,
    reqCameraGet,
    reqCameralogin,
    reqFloorById,
    reqCamerdeviceList,
    reqCamerurl
} from '../../../request/api'
Page({
    data: {
        playUrl: "https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8",
        openDoor: false, //开门告警
        closeDoor: false, //关门告警
        height: '480rpx',
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        deviceInfo: {},
        dataList: [],
        page: 1,
        isNextPage: true, //是否下一页
        triggered: false, //是否下拉刷新列表
        srcFraredActive: '/statics/images/device/infrared_active.png',
        srcInfraredActive: '/statics/images/device/infrared_inactive.png',
        show: false,
        showStatus: false,
        showStatus2: false,
        serviceTypeList: [{
            id: 'work_mode',
            text: '工作模式',
        }, ],
        serviceTypeList2: [{
            id: 'muffling_cmd',
            text: '消音下发',
        }, {
            id: 'temperature_throshold',
            text: '温度阈值设置',
        }, {
            id: 'heartbeat_time',
            text: '心跳周期设置',
        }, ],
        serviceValueList: [{
            id: 0,
            text: '普通模式',
        }, {
            id: 1,
            text: '实时上报模式',
        }, {
            id: 2,
            text: '活动量统计模式',
        }, {
            id: 3,
            text: '建行模式',
        }, {
            id: 4,
            text: '三小场所模式',
        }, {
            id: 5,
            text: '老人独居模式',
        }, ],
        serviceValueList2: [{
            id: 1,
            text: '消音',
        }, ],
        serviceType: "work_mode",
        serviceValue: "0",
        serviceTypename: "工作模式",
        serviceValuename: "普通模式",
        src: "",
        username: "",
        password: "",
        access_token: "",
        deviceMac:""
    },
    // onLoad(e) {
    //     // console.log(e.info);
    //     console.log(JSON.parse(e.info));
    //     let item =e.info
    //     this.setData({
    //           src:`http://192.168.1.111:8080/HomeView?deviceInfo=${item}`,
    //         // src:`${ app.globalData.videoUrl}/?sn=${opation.sn}`
    //     })
    // },
    async onLoad(e) {
        // console.log(e.info);
        console.log(JSON.parse(e.info));
        let item = JSON.parse(e.info)

        this.getDeviceInfo(e)
        await this.CameraGet()
        await this.Cameralogin()
        await this.CamerdeviceList()
        await this.Camerurl()
        await this.playHttpFlv()
        if (item.deviceType == 'DoorMagnetism') {
            this.setData({
                height: '480rpx'
            })
        } else {
            this.setData({
                height: '350rpx'
            })
        }
        // if (item.openDoor == 0) {
        //     this.setData({
        //         openDoor: false
        //     })
        // } else {
        //     this.setData({
        //         openDoor: true
        //     })
        // }
        // if (item.closeDoor == 0) {
        //     this.setData({
        //         closeDoor: false
        //     })
        // } else {
        //     this.setData({
        //         closeDoor: true
        //     })
        // }
    },
     // 平面图
     async addbind(){
        const res = await reqFloorById(this.data.deviceInfo.spaceId)
        if (res.code !== 20000) return showMsg(res.message)
        // console.log(res);
        if(res.data.rows.image=='') return showMsg('当前楼层暂无平面图，请上传后再标记')
        wx.navigateTo({
          url: `../ichnography/ichnography?id=${this.data.deviceInfo.id}&mark=${this.data.deviceInfo.mark}&image=${res.data.rows.image}`,
        })
    },
    // 获取摄像头账号密码
    async CameraGet() {
        const res = await reqCameraGet()
        if (res.code !== 20000) return showMsg(res.message)
        // console.log(res);
        this.setData({
            username: res.data.rows.username,
            password: res.data.rows.password
        })
    },
    // 摄像头账号登录
    async Cameralogin() {
        const res = await reqCameralogin({
            username: this.data.username,
            password: this.data.password
        })
        if (res.code !== 20000) return showMsg(res.message)
        // console.log(res);
        this.setData({
            access_token: res.data.row.access_token
        })
    },
    // 获取设备列表
    async CamerdeviceList() {
        const res = await reqCamerdeviceList({
            token: this.data.access_token,
            deviceMac: "0011040682a7",
            current: "1",
            size: "10",
        })
        if (res.code !== 20000) return showMsg(res.message)
        // console.log(res);
        this.setData({
            deviceMac: res.data.row[0].deviceMac
        })
    },
    // 获取设备播放url地址
    async Camerurl() {
        const res = await reqCamerurl({
            token: this.data.access_token,
            deviceToken:'058fd76550e048d8b5657c7c78595c7a',
            deviceType: "0",
            deviceId: this.data.deviceMac,
            schema: "0",
            type: "0"
        })
        if (res.code !== 20000) return showMsg(res.message)
        // console.log(res);
        this.setData({
            playUrl: res.data.row.url
        })
    },

    statechange(e) {
        console.log('live-player code:', e)
    },
    error(e) {
        console.error('live-player error:', e)
      },
    onNetStatus() {},
    getLivePlayerContext(callback) {
        wx.createSelectorQuery().select('#livePlayerEle').context(function (res) {
            console.log(res.context) // 节点对应的 Context 对象。如：选中的节点是 <video> 组件，那么此处即返回 VideoContext 对象
            callback(res.context)
        }).exec();
    },
    playHttpFlv() {
        //     if (this.apiStartTime) this.printMsg('请求播放地址耗时：' + (Date.now() - this.apiStartTime))
        let url = this.data.playUrl;
        this.setData({
            playUrl: url,
        }, function () {
            this.playStartTime = Date.now();
            this.getLivePlayerContext((context) => {
                context.play({
                    success: () => {
                        console.log(123123);
                        this.printMsg('发起连接')
                    },
                    fail: this.error
                })
            })
        })
    },

    // 获取imei
    getDeviceInfo(e) {
        let item = JSON.parse(e.info)
        this.setData({
            deviceInfo: item
        })
        console.log(item);
        this.getDataList()
    },
    async getDataList() {
        let params = {
            imei: this.data.deviceInfo.imei,
            spaceId: this.data.deviceInfo.spaceId
        }
        let {
            deviceType
        } = this.data.deviceInfo
        if (deviceType === "DoorMagnetism") {
            // 门磁
            const res = await reqDoorList(this.data.page, 10, params)
            if (res.code !== 20000) return showMsg(res.message)
            let {
                rows
            } = res.data
            if (this.data.page === 1) {
                this.setData({
                    dataList: rows,
                    isNextPage: true
                })
            } else if (this.data.page > 1 && rows.length) {
                this.setData({
                    dataList: this.data.dataList.concat(rows),
                    isNextPage: true
                })
            } else if (this.data.page > 1 && !rows.length) {
                showMsg('已经到底啦~')
                this.setData({
                    isNextPage: false
                })
            }
        } else if (deviceType === "Infrared") {
            // 红外
            const res = await reqInfraredList(this.data.page, 10, params)
            if (res.code !== 20000) return showMsg(res.message)
            let {
                rows
            } = res.data
            if (this.data.page === 1) {
                this.setData({
                    dataList: rows,
                    isNextPage: true
                })
            } else if (this.data.page > 1 && rows.length) {
                this.setData({
                    dataList: this.data.dataList.concat(rows),
                    isNextPage: true
                })
            } else if (this.data.page > 1 && !rows.length) {
                showMsg('已经到底啦~')
                this.setData({
                    isNextPage: false
                })
            }
        } else {
            return
        }
    },
    // 滚动到底部触发
    lower() {
        if (!this.data.isNextPage) return
        this.setData({
            page: this.data.page + 1,
        })
        this.getDataList()
    },
    // 下拉刷新
    async onRefresh() {
        this.setData({
            dataList: [],
            page: 1,
            isNextPage: true,
            triggered: true,
        })
        await this.getDataList()
        this.setData({
            triggered: false,
        })
    },

    // 下发指令开始
    goAlarmDetail() {
        if (this.data.deviceInfo.deviceType == 'SmokeAlarm') {
            this.setData({
                serviceType: "muffling_cmd",
                serviceValue: 1,
                serviceTypename: "消音下发",
                serviceValuename: "消音",
                show: true,
            })
        } else if (this.data.deviceInfo.deviceType == 'Infrared') {
            this.setData({
                serviceType: "work_mode",
                serviceValue: "0",
                serviceTypename: "工作模式",
                serviceValuename: "普通模式",
                show: true,
            })
        }
    },
    onClose() {
        this.setData({
            show: false,
        });
    },
    async bindtapShoudon() {
        if (this.data.serviceValue == '') return showMsg('服务值不能为空')
        const res = await reqCommand({
            deviceId: this.data.deviceInfo.deviceId,
            imei: this.data.deviceInfo.imei,
            serviceType: this.data.serviceType,
            serviceValue: this.data.serviceValue,
        })
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        this.setData({
            show: false,
        });
        showMsg('下发指令成功！')
    },
    Clickstatus() {
        this.setData({
            showStatus: true
        })
    },
    Clickstatus2() {
        this.setData({
            showStatus2: true
        })
    },
    statusConfirm(e) {
        const {
            value,
        } = e.detail;
        console.log(value);
        this.setData({
            "serviceType": value.id,
            "serviceTypename": value.text,
            showStatus: false,
        })
        if (value.id == 'temperature_throshold' || value.id == 'heartbeat_time') {
            this.setData({
                serviceValue: ""
            })
        } else if (value.id == 'muffling_cmd') {
            this.setData({
                serviceValue: "1"
            })
        } else if (value.id == 'work_mode') {
            this.setData({
                serviceValue: "0"
            })
        }
    },
    statusClose() {
        this.setData({
            showStatus: false
        })
    },
    statusConfirm2(e) {
        const {
            value,
        } = e.detail;
        this.setData({
            "serviceValue": value.id,
            "serviceValuename": value.text,
            showStatus2: false,
        })
    },
    statusClose2() {
        this.setData({
            showStatus2: false
        })
    },
})